program onehalf
	
	implicit NONE
	
	character(255)			:: foldr = 'D:\Users\Eliah\Documents\WORK\TestProjects\Mott Insulator\CorrelationTime\'
	
	integer(4)				:: sts, iunit
	integer(4)				:: fsz, nsz
	
	real(8), allocatable	:: ncc(:)
	real(8), allocatable	:: nmn(:)
	real(8), allocatable	:: nmx(:)
	
	real(8)					:: cmin, cmax
	integer(4)				:: imi, ima
	
	integer(4)				:: idd, i2
	
!!====================================================================================================================
	
	open( newunit = iunit, file = trim(foldr) // 'nc.bin', access = 'stream', action = 'read', status = 'old', iostat = sts)
	
	inquire( iunit, size = fsz)
	
	nsz = fsz / 8
	
	allocate( ncc(nsz), stat = sts)
	read( iunit) ncc
	
	close( iunit)
	allocate( nmn(nsz), nmx(nsz), stat = sts)
	
	nmn(1) = ncc(1)
	nmx(1) = ncc(1)
	
!	do idd = 2, nsz
!		
!		i2 = idd / 2
!		nmn(idd) = minval( ncc(i2+1:idd))
!		nmx(idd) = maxval( ncc(i2+1:idd))
!		
!	end do
	
	imi = 1
	ima = 1
	cmin = ncc(1)
	cmax = ncc(2)
	
	do idd = 2, nsz
		
		i2 = idd / 2
		
		if ( imi <= i2) then
			imi = i2 + minloc( ncc(i2+1:idd), dim = 1)
			cmin = ncc(imi)
		else if ( ncc(idd) < cmin) then
				imi = idd
				cmin = ncc(idd)
		end if
		
		if ( ima <= i2) then
			ima = i2 + maxloc( ncc(i2+1:idd), dim = 1)
			cmax = ncc(ima)
		else if ( ncc(idd) > cmax) then
				ima = idd
				cmax = ncc(idd)
		end if
		
		nmn(idd) = cmin
		nmx(idd) = cmax
		
	end do
	
	deallocate(ncc)
	
	open( newunit = iunit, file = trim(foldr) // 'nmx.bin', access = 'stream', action = 'write', status = 'replace', iostat = sts)
	write( iunit) nmx
	close( iunit)
	
	open( newunit = iunit, file = trim(foldr) // 'nmn.bin', access = 'stream', action = 'write', status = 'replace', iostat = sts)
	write( iunit) nmn
	close( iunit)
	
	deallocate(nmn)
	deallocate(nmx)
	
end program onehalf